﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HitchHikersGuideToTheGalaxy.Models
{
    public class GradeRepositiory : IGradeRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Default Add, Delete and save actions

        /// <summary>
        /// Add a Grade
        /// </summary>
        /// <param name="grade">Grade object</param>
        public void Add(Grade grade)
        {
            db.Grades.InsertOnSubmit(grade);
        }

        /// <summary>
        /// Delete a Grade
        /// </summary>
        /// <param name="grade">Grade object</param>
        public void Delete(Grade grade)
        {
            db.Grades.DeleteOnSubmit(grade);
        }

        /// <summary>
        /// Save to database
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        #region Querys

        /// <summary>
        /// Find all Grades
        /// </summary>
        /// <returns>Grade collection</returns>
        public IQueryable<Grade> FindAllGrades()
        {
            return db.Grades;
        }

        /// <summary>
        /// Get Grade by ID
        /// </summary>
        /// <param name="id">Id of grade</param>
        /// <returns>Grade name</returns>
        public Grade GetGrade(int id)
        {
            return db.Grades.SingleOrDefault(d => d.Id == id);
        }

        /// <summary>
        /// Get Id of grade
        /// </summary>
        /// <param name="grade">Grade name</param>
        /// <returns>Id of grade</returns>
        public int GetRankById(int rank)
        {
            return (from a in db.Grades
                    where a.Rank == rank
                    select a.Id).SingleOrDefault();
        }

        #endregion
    }
}
